package paper.db;

import java.sql.*;

import java.io.PrintWriter;
import java.io.File;

import java.util.HashSet;
import java.util.Random;
import java.util.Iterator;

import paper.db.DB;

public class PDFFile {
    public Paper paper;
    public String  md5;
    public boolean copyrighted;
    public boolean hasTitle;
    public boolean analysed;
    public String  date;
    public String  data;
    public String  authors;
    public String  title;
    public String  email;
    public String  howpublished;
    
    public PDFFile(String md5, Paper p, boolean analysed,
                   boolean copyrighted, boolean hasTitle, String data,
                   String authors, String title, String email,
                   String howpublished) {
        this.md5 = md5;
        this.paper = p;
        this.analysed = analysed;
        this.copyrighted = copyrighted;
        this.hasTitle = hasTitle;
        this.data   = data;
        this.authors= authors;
        this.title  = title;
        this.email  = email;
        this.howpublished = howpublished;
    }

    private PDFFile() {
    }

    public void setMD5(String md5) {
        this.md5 = md5;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    // Dealings with persistent data.

    public static void main(String[] args) {
    }

    static public PDFFile loadOnPaperKey(String key, PaperIndex c) {
        return loadInternal(" WHERE p.paperkey = '" + DB.q(key,16) + "'",c);
    }

    static public PDFFile loadOnMD5(String md5, PaperIndex c) {
        return loadInternal(" WHERE p.md5 = '" + DB.q(md5,DB.md5Max) + "'",c);
    }

    private static PDFFile loadInternal(String where, PaperIndex c) {
        try {
            Statement st = DB.connection.createStatement();
            ResultSet rs = st.executeQuery("SELECT p.* FROM pdffiles p " + where);
            if (rs.next()) {
                PDFFile p       = new PDFFile();
                p.md5           = rs.getString(DB.md5);
                p.date          = rs.getString(DB.date);
                p.analysed      = rs.getString(DB.analysed).equals("1");
                p.copyrighted   = rs.getString(DB.copyrighted).equals("1");
                p.authors       = rs.getString(DB.authors);
                p.title         = rs.getString(DB.title);
                p.email         = rs.getString(DB.email);
                p.howpublished  = rs.getString(DB.howpublished);
                String paperKey = rs.getString(DB.paperKey);
                if (!paperKey.equals("")) {
                    p.paper     = Paper.loadOnKey(paperKey, c);
                }
                return p;
            }
            st.close();
        } catch (SQLException e) {
            System.err.println("Failed to load md5 entry " + where + " " + e);
        }
        return null;
    }


    public void commit() {
        date = DB.today();
        Statement st = null;
        String query = null;
        try {
            st = DB.connection.createStatement();
            st.executeUpdate("DELETE FROM pdffiles WHERE md5='" +
                             DB.q(md5,DB.md5Max) +"'");
            query = ("INSERT INTO pdffiles " +
                     "(md5,paperkey,analysed,authors,title,email,howpublished,date,data,copyrighted) " +
                     "VALUES ('"+ DB.q(md5,DB.md5Max) +"'," +
                     "'"+ (paper == null ? "" : DB.q(paper.key,DB.paperKeyMax)) +"'," + 
                     "'"+ (analysed?"1":"0") +"'," + 
                     "'"+ DB.q(Paper.sanitise(authors),DB.authorsMax) +"'," +
                     "'"+ DB.q(Paper.sanitise(title),DB.titleMax) +"'," +
                     "'"+ DB.q(email,DB.emailMax) +"'," +
                     "'"+ DB.q(howpublished,DB.howpublishedMax) +"'," +
                     "'"+ DB.q(date,DB.dateMax) +"'," +
                     "'"+ DB.q(data,65536) +"'," +
                     "'"+ (copyrighted?"1":"0")+"')");
            st.executeUpdate(query);
        } catch (SQLException e) {
            System.err.println("Failed to update " + md5 + ": " + e + " ---" + query + "---");
        } finally {
            try {
                if (st != null) st.close();
            } catch(Exception e) {
                System.err.println("Fuck..." + e);
            }
        }
    }

    static public File getThumbnail(String md5){
        return getSuffix(md5, "-thumb.png");
    }

    static public File getImg(String md5){
        return getSuffix(md5, ".png");
    }

    static public File getFile(String md5) {
        return getSuffix(md5, ".pdf");
    }

    static public File getText(String md5) {
        return getSuffix(md5, ".txt");
    }

    static private File getSuffix(String md5, String suffix) {
        return new File(getDir(md5), md5 + suffix);
    }

    static public File baseDir = new File("nobackup/pdfarchive");

    static public File getDir(String md5) {
        return new File(baseDir, md5.substring(0,2)+ "/" + md5.substring(2,4));
    }


    // Local functions

    public String toString() {
        return md5 + ": " + paper;
    }

}
